package com.beiing.tianshuai.tianshuai.message.ui;

import android.content.Context;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.beiing.tianshuai.tianshuai.R;
import com.beiing.tianshuai.tianshuai.adapter.SearchContactListAdapter;
import com.beiing.tianshuai.tianshuai.base.BaseActivity;
import com.beiing.tianshuai.tianshuai.entity.ConversationListInfo;
import com.beiing.tianshuai.tianshuai.nim.session.SessionHelper;
import com.beiing.tianshuai.tianshuai.util.LogUtils;
import com.beiing.tianshuai.tianshuai.widget.RecycleViewDivider;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.RequestCallback;
import com.netease.nimlib.sdk.msg.MsgService;
import com.netease.nimlib.sdk.msg.constant.SessionTypeEnum;
import com.netease.nimlib.sdk.msg.model.RecentContact;
import com.netease.nimlib.sdk.team.TeamService;
import com.netease.nimlib.sdk.team.model.Team;
import com.netease.nimlib.sdk.uinfo.UserService;
import com.netease.nimlib.sdk.uinfo.model.NimUserInfo;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import cn.bingoogolapple.bgabanner.BGAOnNoDoubleClickListener;

public class SearchContactActivity extends BaseActivity {

    @BindView(R.id.toolbar_iv_back)
    ImageView mToolbarIvBack;
    @BindView(R.id.toolbar_btn_publish)
    TextView mToolbarBtnSearch;
    @BindView(R.id.et_search_content)
    EditText mEtSearchContent;
    @BindView(R.id.rv_contact_list)
    RecyclerView mListView;

    private static final String TAG = "SearchContactActivity";
    private Unbinder mUnbinder;
    private Context mContext;
    private List<ConversationListInfo> mSearchResult;
    private SearchContactListAdapter mAdapter;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_search_contact;
    }

    @Override
    protected void init() {
        mUnbinder = ButterKnife.bind(this);
        mContext = this;
        initToolbar();
        initRecyclerView();
        initListener();
    }

    private void initToolbar() {
        mToolbarIvBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (inputMethodManager != null) {
                    inputMethodManager.hideSoftInputFromWindow(mEtSearchContent != null ? mEtSearchContent.getWindowToken() : null, 0);
                }
                finish();
            }
        });
    }

    private void initRecyclerView() {
        mAdapter = new SearchContactListAdapter(mContext);
        mListView.setAdapter(mAdapter);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mContext);
        mListView.setNestedScrollingEnabled(false);
        mListView.setLayoutManager(linearLayoutManager);
        //绘制item间的分割线，
        mListView.addItemDecoration(
                new RecycleViewDivider(
                        mContext, LinearLayoutManager.HORIZONTAL, 1,
                        ContextCompat.getColor(mContext, R.color.common_gray_background))
        );
    }

    private void initListener() {
        // 给输入框设置输入监听事件
        mEtSearchContent.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                String keyWord = editable.toString();
                if (!TextUtils.isEmpty(keyWord)) {
                    searchContact();
                }
            }
        });

        // 给输入框设置软键盘搜索事件
        mEtSearchContent.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
                if (i == EditorInfo.IME_ACTION_SEARCH) {
                    if (!TextUtils.isEmpty(mEtSearchContent.getText().toString())) {
                        searchContact();
                    /*隐藏软键盘*/
                        InputMethodManager imm = (InputMethodManager) textView.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                        if (imm != null && imm.isActive()) {
                            imm.hideSoftInputFromWindow(textView.getApplicationWindowToken(), 0);
                        }
                        return true;
                    } else {
                        showShortText("请输入关键字");
                    }
                }
                return false;
            }
        });

        // 搜索按钮
        mToolbarBtnSearch.setOnClickListener(new BGAOnNoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                if (!TextUtils.isEmpty(mEtSearchContent.getText())) {
                    searchContact();
                }
            }
        });

        // 消息列表
        mAdapter.setListener(
                new SearchContactListAdapter.OnItemClickListener() {
                    @Override
                    public void onItemClickListener(String uid, int chatType) {
                        if (chatType == SessionTypeEnum.P2P.getValue()) {
                            SessionHelper.startP2PSession(mContext, uid);
                        } else if (chatType == SessionTypeEnum.Team.getValue()) {
                            SessionHelper.startTeamSession(mContext, uid);
                        }
                        finish();
                    }
                }
        );
    }

    /**
     * 搜索最近会话中的目标用户
     */
    private void searchContact() {
        mSearchResult = new ArrayList<>();
        final String keyWord = mEtSearchContent.getText().toString();
        NIMClient.getService(MsgService.class).queryRecentContacts()
                .setCallback(new RequestCallback<List<RecentContact>>() {
                    @Override
                    public void onSuccess(List<RecentContact> recentContacts) {
                        if (!recentContacts.isEmpty()) {
                            for (RecentContact recentContact : recentContacts) {
                                String uid = recentContact.getContactId();
                                SessionTypeEnum sessionType = recentContact.getSessionType();
                                if (sessionType == SessionTypeEnum.P2P) {
                                    NimUserInfo userInfo = NIMClient.getService(UserService.class).getUserInfo(uid);
                                    checkAndAddRecentContacts(recentContact, userInfo);
                                } else if (sessionType == SessionTypeEnum.Team) {
                                    Team team = NIMClient.getService(TeamService.class).queryTeamBlock(uid);
                                    checkAndAddRecentContacts(recentContact, team);
                                }
                            }
                            mAdapter.updateData(mSearchResult);
                        }
                    }

                    /**
                     * 获取P2P类型最近会话详情
                     *
                     * @param recentContact 最近会话
                     * @param userInfo 最近会话用户信息
                     */
                    private void checkAndAddRecentContacts(RecentContact recentContact, NimUserInfo userInfo) {
                        String uid = recentContact.getContactId();
                        String name = userInfo.getName();
                        SessionTypeEnum sessionType = recentContact.getSessionType();
                        // 判断是否属于用户搜索范围内的会话联系人
                        if (name.contains(keyWord)) {
                            // 获取联系人详情信息
                            int sessionTypeValue = sessionType.getValue();
                            String content = recentContact.getContent();
                            long time = recentContact.getTime();
                            String avatar = userInfo.getAvatar();
                            int unreadCount = recentContact.getUnreadCount();

                            // 创建一个新的联系人对象
                            ConversationListInfo conversationListInfo = new ConversationListInfo();
                            conversationListInfo.setLastMessage(content);
                            conversationListInfo.setType(sessionTypeValue);
                            conversationListInfo.setTime(time);
                            conversationListInfo.setUid(uid);
                            conversationListInfo.setAvatar(avatar);
                            conversationListInfo.setNickname(name);
                            conversationListInfo.setUnreadMessageCount(unreadCount);

                            // 将联系人添加到集合中
                            mSearchResult.add(conversationListInfo);
                        }
                    }

                    /**
                     * 获取Team类型最近会话详情信息
                     *
                     * @param recentContact 最近会话
                     * @param team 最近会话群组详情
                     */
                    private void checkAndAddRecentContacts(RecentContact recentContact, Team team) {
                        String uid = recentContact.getContactId();
                        String name = team.getName();
                        SessionTypeEnum sessionType = recentContact.getSessionType();
                        // 判断是否属于用户搜索范围内的会话联系人
                        if (name.contains(keyWord)) {
                            // 获取联系人详情信息
                            int sessionTypeValue = sessionType.getValue();
                            String content = recentContact.getContent();
                            long time = recentContact.getTime();
                            String avatar = team.getIcon();
                            int unreadCount = recentContact.getUnreadCount();

                            // 创建一个新的联系人对象
                            ConversationListInfo conversationListInfo = new ConversationListInfo();
                            conversationListInfo.setLastMessage(content);
                            conversationListInfo.setType(sessionTypeValue);
                            conversationListInfo.setTime(time);
                            conversationListInfo.setUid(uid);
                            conversationListInfo.setAvatar(avatar);
                            conversationListInfo.setNickname(name);
                            conversationListInfo.setUnreadMessageCount(unreadCount);

                            // 将联系人添加到集合中
                            mSearchResult.add(conversationListInfo);
                        }
                    }

                    @Override
                    public void onFailed(int i) {
                        LogUtils.e("queryRecentContacts onFailed : " + i, TAG);
                    }

                    @Override
                    public void onException(Throwable throwable) {
                        LogUtils.e(throwable.getMessage(), TAG);
                    }
                });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mUnbinder != null) {
            mUnbinder.unbind();
        }
    }
}
